from io import BytesIO
from PIL import Image, ImageDraw, ImageFont
import random

# def valid_code():
#   def get_random_color():
#     return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
#   img = Image.new('RGB', (270, 40), color=get_random_color())

#   with open('validImag.png', 'wb') as f:
#     img.save(f, 'png')

#   with open('validImag.png', 'rb') as f:
#     data = f.read()
  
#   return data

def valid_code():
  def get_random_color():
    return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
  img = Image.new('RGB', (270, 40), color=get_random_color())
  draw = ImageDraw.Draw(img)
  font = ImageFont.truetype('static/font/msyh.ttf', size=40)
  char = '1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKL'
  char_len = len(char)
  chars = ''
  for i in range(5):
    char_result = char[random.randint(0, char_len-1)]
    chars += char_result
    draw.text((i*50, -10), char_result, get_random_color(), font=font)

  # width = 270
  # height = 40

  # for i in range(10):
  #   x1 = random.randint(0, width)
  #   y1 = random.randint(0,height)
  #   x2 = random.randint(0, width)
  #   y2 = random.randint(0,height)
  #   draw.line((x1, y1, x2, y2), fill=get_random_color())

  # for i in range(100):
  #   draw.point([random.randint(0, width), random.randint(0, height)], fill=get_random_color())
  #   x = random.randint(0, width)
  #   y = random.randint(0, height)
  #   draw.arc((x, y, x+4, x+4), 0, 90, fill=get_random_color())
  

  f = BytesIO()
  img.save(f, 'png')
  data = f.getvalue()
  return [data, chars]
